package com.tarzan.cms.modules.admin.service.oss;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarzan.cms.modules.admin.mapper.oss.OssConfigMapper;
import com.tarzan.cms.modules.admin.model.oss.OssConfig;
import com.tarzan.cms.modules.admin.vo.CloudStorageConfigVo;
import com.tarzan.cms.utils.BeanUtil;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tarzam
 */
@Service
public class OssConfigService extends ServiceImpl<OssConfigMapper, OssConfig> {

   // @Cacheable(value = "oss", key = "'config'")
    public Map<String, Object> selectAll() {
        List<OssConfig> ossConfigs =super.list();
        Map<String, Object> map = new HashMap<>(ossConfigs.size());
        for (OssConfig config : ossConfigs) {
            if("type".equals(config.getSysKey())){
                map.put(config.getSysKey(), Integer.parseInt(config.getSysValue()));
            }else {
                map.put(config.getSysKey(), config.getSysValue());
            }
        }
        return map;
    }

    @CacheEvict(value = "oss", key = "'config'", allEntries = true)
    public boolean updateByKey(String key, String value) {
        if (getOne(Wrappers.<OssConfig>lambdaQuery().eq(OssConfig::getSysKey, key)) != null) {
            return update(Wrappers.<OssConfig>lambdaUpdate().eq(OssConfig::getSysKey, key).set(OssConfig::getSysValue, value));
        } else {
            return save(new OssConfig().setSysKey(key).setSysValue(value));
        }
    }

    @CacheEvict(value = "oss", key = "'config'", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAll(Map<String, String> map) {
        boolean flag=true;
        for (Map.Entry<String,String> entry: map.entrySet()) {
            if(!updateByKey(entry.getKey(),entry.getValue())){
                flag=false;
            }
        }
        return flag;
    }

   // @Cacheable(value = "oss", key = "'config'")
    public CloudStorageConfigVo getConfig() {
        Map<String, Object> map = this.selectAll();
        return BeanUtil.toBean(map,new CloudStorageConfigVo());
    }


}
